#include "app_runner.h"
#include "app_pool.h"
#include "app_router.h"
#include "app_serial.h"
#include <signal.h>

static is_running=1;

static void stop_signal_handler(int signum)
{
    log_info("stop_signal_handler");
    is_running=0;
}

void app_runner_run()
{
    // 接收停止信号
    signal(SIGINT, stop_signal_handler); // ctrl+c
    signal(SIGTERM, stop_signal_handler); //kill

    log_info("app_runner_run");
    //通过路径创建设备
    SerialDevice *device= app_serial_device_Init(SERIAL_FILENAME);
    if( device == NULL )
    {
        log_error("app_serial_device_Init failed");
        return;
    }

    //为串口设备设置连接类型
    if( app_serial_device_set_connection_type(device, CONN_BT))
    {
        log_error("app_serial_device_set_connection_type failed");
        goto AFTER_DEVICE_INIT;
    }

    //创建router   
    if(app_router_init()<0)
    {
        log_error("app_router_init failed");
        goto AFTER_DEVICE_INIT;
    }


    //向router注册设备 
    if(app_router_register_device(device)<0)
    {
        log_error("app_router_register_device failed");
        goto AFTER_ROUTER_INIT;
    }

    //创建连接池 
    if(app_pool_init(5)<0)
    {
        log_error("app_router_register_device failed");
        goto AFTER_ROUTER_INIT;
    }
  
    while(is_running)
    {
       usleep(100000);
    }


AFTER_ROUTER_INIT:
     app_router_close();
AFTER_DEVICE_INIT:
     app_device_close(device);
    return 0;
}